package licode.unisop.realm.application.service;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 实现设备的远程调用适配接口
 *
 * @author WR
 */
@Component
public class SiRestfulCallUtil {
    private static final int CONN_TIMEOUT = 3000;
    private static final int READ_TIMEOUT = 60000;

    private static final ClientHttpRequestFactory DEF_CONFIG = configSetting(READ_TIMEOUT);

    @Resource
    @Qualifier("siRestTemplate")
    private RestTemplate siRestTemplate;

    public  <R, T> R post(Map<String, String> params, Class<R> rCls, T req, String url) {
        return this.post(params, rCls, req, url, null);
    }

    public  <R, T> R post(Map<String, String> params, Class<R> rCls, T req, String url, Integer readTimeout) {
        HttpHeaders httpHeaders = new HttpHeaders();

        if (null != params) {
            params.forEach(httpHeaders::set);
        }

        httpHeaders.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<T> httpEntity = new HttpEntity<>(req, httpHeaders);
        String postUrl = buildUrl(url);
        ResponseEntity<R> resEntity;

        if (null == readTimeout) {
            siRestTemplate.setRequestFactory(DEF_CONFIG);
        } else {
            siRestTemplate.setRequestFactory(configSetting(readTimeout));
        }

        resEntity = siRestTemplate.postForEntity(postUrl, httpEntity, rCls);

        return resEntity.getBody();
    }

    private static ClientHttpRequestFactory configSetting(int readTimeout) {
        SimpleClientHttpRequestFactory requestFactory;
        requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(SiRestfulCallUtil.CONN_TIMEOUT);
        requestFactory.setReadTimeout(readTimeout);
        return requestFactory;
    }

    private String buildUrl(String url) {
        String retUrl;

        if (url.startsWith("http")) {
            retUrl = url;
        } else {
            retUrl = "http://" + url;
        }

        return retUrl;
    }
}
